import React, { useContext, useState } from 'react'
import styles from './index.module.scss'
import { Context } from '../../App'
import bag from '../../assets/imgs/bag.png'
import classnames from 'classnames'
import CartDetail from './CartDetail'
import Checkout from '../Checkout'

export default function Cart() {
	const { cartData } = useContext(Context)
	const [showCartDetail, setshowCartDetail] = useState(false)
	const [showCheckout, setShowCheckout] = useState(false)

	const toggleCartDetailHandler = () => {
		setshowCartDetail(showCartDetail => !showCartDetail)
	}

	const showCheckoutHandler = () => {
		setShowCheckout(true)
	}

	const cancelCheckoutHandler = () => {
		setShowCheckout(false)
	}

	return (
        <div className={styles.root} onClick={toggleCartDetailHandler}>
			{showCheckout&& <Checkout cancel={cancelCheckoutHandler} />}

			{showCartDetail && <CartDetail cancelDetail={() => setshowCartDetail(false)} />}
            
			<div className="icon">
				<img src={bag} alt="" />
				{cartData.totalTotal !== 0 ? (
					<span className="totalTotal">{cartData.totalTotal}</span>
				) : null}
			</div>
			{cartData.totalTotal !== 0 ? (
				<p className="totalPrice">{cartData.totalPrice}</p>
			) : (
				<p className="noMeal">未选择商品</p>
			)}

			<button onClick={showCheckoutHandler} className={classnames('buyBtn', cartData.totalTotal === 0? 'disabled': '')} disabled={cartData.totalTotal === 0}>去结算</button>
		</div>
	)
}
